package com.xmkj.bearbiz.jifen;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.Entity.DuoBaoDetailsEntity;
import com.common.Entity.HomeEntity;
import com.common.Entity.ShareEntity;
import com.common.adapter.helper.IRecyclerViewHelper;
import com.common.banner.CBViewHolderCreator;
import com.common.banner.ConvenientBanner;
import com.common.banner.OnItemClickListener;
import com.common.base.Config;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.method.DuoBaoDetailMethods;
import com.common.retrofit.method.GetShareDatasMethods;
import com.common.retrofit.method.ShareSuccessMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.SPUtils;
import com.common.utils.SizeUtils;
import com.common.widget.DividerDecoration.MarginDecoration;
import com.common.widget.imageview.image.ImageLoaderUtils;
import com.common.widget.navigation.WidgetButton;
import com.common.widget.recyclerview.refresh.recycleview.XRecyclerView;
import com.xmkj.payandlogin.ShareConfig;
import com.xmkj.payandlogin.ShareManager;
import com.xmkj.payandlogin.ShareUtil;
import com.xmkj.payandlogin.share.ShareListener;
import com.xmkj.payandlogin.share.SharePlatform;
import com.xmkj.bearbiz.R;
import com.xmkj.bearbiz.TempItemBean;
import com.xmkj.bearbiz.home.NetworkImageHolderView;
import com.xmkj.bearbiz.view.FolderTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

public class AwardDelActivity extends BaseMvpActivity implements OnItemClickListener {
    public static final String TEMPBEAN = "tempbean";
    @BindView(R.id.home_view_pager)
    ConvenientBanner homeViewPager;
    @BindView(R.id.tv_stasus)
    TextView tvStasus;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.tv_chui)
    TextView tvChui;
    @BindView(R.id.tv_qishu)
    TextView tvQishu;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.tv_renci)
    TextView tvRenci;
    @BindView(R.id.tv_remain)
    TextView tvRemain;
    @BindView(R.id.tv_not_in)
    TextView tvNotIn;
    @BindView(R.id.ft_numbers)
    FolderTextView ftNumbers;
    @BindView(R.id.ll_in)
    LinearLayout llIn;
    @BindView(R.id.iv_next)
    ImageView ivNext;
    @BindView(R.id.rl_img_details)
    RelativeLayout rlImgDetails;
    @BindView(R.id.iv_next1)
    ImageView ivNext1;
    @BindView(R.id.rl_last)
    RelativeLayout rlLast;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rl_records)
    RelativeLayout rlRecords;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerview;
    @BindView(R.id.tv_get_jifen)
    TextView tvGetJifen;
    @BindView(R.id.tv_support)
    TextView tvSupport;
    List<DuoBaoDetailsEntity.AllRecordBean> bean = new ArrayList<>();
    @BindView(R.id.rl_on)
    RelativeLayout rlOn;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_qihao)
    TextView tvQihao;
    @BindView(R.id.tv_finish_renci)
    TextView tvFinishRenci;
    @BindView(R.id.tv_finish_time)
    TextView tvFinishTime;
    @BindView(R.id.tv_lucky_num)
    TextView tvLuckyNum;
    @BindView(R.id.tv_jisuan_details)
    TextView tvJisuanDetails;
    @BindView(R.id.rl_finish)
    RelativeLayout rlFinish;
    @BindView(R.id.tv_my_in)
    TextView tvMyInjoin;
    @BindView(R.id.tv_go)
    TextView tvGo;
    @BindView(R.id.rl_next)
    RelativeLayout rlNext;
    @BindView(R.id.ll_on)
    LinearLayout llOn;

    private List<String> viewPagerUrl = new ArrayList<>();
    private JoinRecordAdapter adapter;
    private TempItemBean tempItemBean;
    private DuoBaoDetailsEntity beans;
    private ShareEntity shareEntity;


    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_award_del;
    }

    @Override
    protected void onViewCreated() {
        setRightImg();
    }

    private void setRightImg() {
        m_navigationBar.setVisibility(View.VISIBLE);
        WidgetButton widgetButton = new WidgetButton(this, getResources().getDrawable(R.mipmap.share_three));

        widgetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            gotoShare();
            }
        });
        m_navigationBar.setRightMenu(widgetButton);
    }

    private void Sharesuccessfully() {
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();

//                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        ShareSuccessMethods.getInstance().shareSuccess(subscriber, uid, hashid);
        rxManager.add(subscriber);
    }
    private ShareListener shareListener = new ShareListener() {
        @Override
        public void shareSuccess() {
            showToastMsg("分享成功");
            Sharesuccessfully();
        }

        @Override
        public void shareFailure(Exception e) {
            showToastMsg("分享失败");
        }

        @Override
        public void shareCancel() {
            showToastMsg("取消分享");
        }
    };
    private void gotoShare() {
        showShareButton();
        setOnShareClick(new OnShareClick() {
            @Override
            public void wechat() {
                if (ShareUtil.isInstalled(SharePlatform.WX, context)) {

//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
//                        ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);
//
//                    } else {
//                        ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    ShareUtil.shareMedia(context, SharePlatform.WX, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);
//                    }

                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void wethatCircle() {
                if (ShareUtil.isInstalled(SharePlatform.WX_TIMELINE, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
//                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);
//
//                    } else {
//                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);

                    ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);
//                    }
                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void qq() {
                if (ShareUtil.isInstalled(SharePlatform.QQ, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
               /*     if (EmptyUtils.isEmpty(mineBean.img)) {
                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);

                    } else {*/
//                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    ShareUtil.shareMedia(context, SharePlatform.QQ, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);

//                    }

                } else {
                    showToastMsg("未安装QQ");
                }
            }
        });
    }

    @Override
    protected void doLogicFunc() {
        ShareConfig config = ShareConfig.instance()
                .qqId(Config.APP_QQ_ID)
                .wxSecret(Config.APP_SERECET)
                .wxId(Config.APP_ID);
        ShareManager.init(config);
        tempItemBean = (TempItemBean) getIntent().getSerializableExtra(TEMPBEAN);
        if (EmptyUtils.isNotEmpty(tempItemBean)) {

            gotoHttpRep();
            setRecyclerView();
        }
        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.DUOBAOSUCEESS)&&(Boolean) rxKeyEvent.getValue()) {
                    if (EmptyUtils.isNotEmpty(tempItemBean)) {
                        gotoHttpRep();
                        setRecyclerView();
                    }

                }
            }
        }));
        getShareData();
        attachClickListener(tvGo);
        attachClickListener(rlLast);
        attachClickListener(rlImgDetails);
        attachClickListener(tvJisuanDetails);
        attachClickListener(tvSupport);
        attachClickListener(tvGetJifen);
        setBanner();
        progress.setSecondaryProgress(25);

    }

    private void getShareData() {
        CommonSubscriber<ShareEntity> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                shareEntity = (ShareEntity) o;

//                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        GetShareDatasMethods.getInstance().share(subscriber, uid, hashid);
        rxManager.add(subscriber);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onViewClicked(View view) {
        if(view.getId()==tvGo.getId()){
            Intent intent = new Intent(context,AwardDelActivity.class);
            TempItemBean tempItemBean = new TempItemBean() ;
            if(EmptyUtils.isNotEmpty(beans.new_activity)){
                tempItemBean.fvid = beans.new_activity.fvid;
                tempItemBean.gid = beans.new_activity.gid ;
                tempItemBean.vid = beans.new_activity.vid ;
            }

            intent.putExtra(AwardDelActivity.TEMPBEAN,tempItemBean);
            startActivity(intent);
        } else if(view.getId()==rlLast.getId()){
            Intent intent = new Intent(context,DuoBaoWangQiActivity.class);
            intent.putExtra(DuoBaoWangQiActivity.TEMPBEAN,tempItemBean);
            startActivity(intent);
        }else if(view.getId()==rlImgDetails.getId()){
            Intent intent = new Intent(context, PhotoDetailsAcitivity.class);
            intent.putExtra(PhotoDetailsAcitivity.GID, tempItemBean.gid + "");
            startActivity(intent);
        } else if(view.getId()==tvJisuanDetails.getId()){
            Intent intent = new Intent(context,JiSuanActivity.class);
            intent.putExtra(JiSuanActivity.TEMPBEAN,tempItemBean);
            startActivity(intent);
        }else if(view.getId()==tvSupport.getId()){
            Intent intent = new Intent(context, UseMoneyJoinAcitivity.class);
            HomeEntity.ListsEntity infoBean = new HomeEntity.ListsEntity();
            infoBean.fvid = tempItemBean.fvid;
            infoBean.gid = Integer.valueOf(tempItemBean.gid);
            infoBean.vid = tempItemBean.vid;
            intent.putExtra(UseMoneyJoinAcitivity.JINGPAIBEAN, infoBean);
            startActivity(intent);
        } else if(view.getId()==tvGetJifen.getId()){
            showToastMsg("请到头条文章打赏获得积分！");
        }
    }

    private int[] page_indicatorId;

    private void setBanner() {
//        viewPagerUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1525427891333&di=32991d497454624b5c490151a185a2c1&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0142135541fe180000019ae9b8cf86.jpg%401280w_1l_2o_100sh.png");
//        viewPagerUrl.add("http://img07.tooopen.com/images/20170316/tooopen_sy_201956178977.jpg");
//        viewPagerUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1525427891333&di=32991d497454624b5c490151a185a2c1&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0142135541fe180000019ae9b8cf86.jpg%401280w_1l_2o_100sh.png");
        if (beans != null && beans.good_info.goods_album.size() > 0&&viewPagerUrl.size()==0) {
            for (int i = 0; i < beans.good_info.goods_album.size(); i++) {
                viewPagerUrl.add(beans.good_info.goods_album.get(i));
            }
        }

        page_indicatorId = new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused};
        homeViewPager.setPageIndicator(page_indicatorId);
        homeViewPager.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, viewPagerUrl);
        homeViewPager.setOnItemClickListener(this);
        homeViewPager.startTurning(5000);
    }

    @Override
    protected void setNavigation() {
        setNavigationBack("奖品详情");
    }


    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    @Override
    public void onItemClick(int position) {

    }

    private void gotoHttpRep() {
        CommonSubscriber<DuoBaoDetailsEntity> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                beans = (DuoBaoDetailsEntity) o;
                tvInfo.setText(beans.good_info.goods_name);
                tvChui.setText(beans.good_info.goods_desc);
                tvTime.setText("("+beans.record_start_time+"开始)");
                setBanner();

                // 显示跟隐藏处理
                if (beans.mybuy_record.size() == 0) {  // 我没有参与
                    tvNotIn.setVisibility(View.VISIBLE);
                    llIn.setVisibility(View.GONE);
                } else {
                    tvNotIn.setVisibility(View.GONE);
                    llIn.setVisibility(View.VISIBLE);
                    tvMyInjoin.setText("您参与了："+beans.mybuy_total+"人次");
                    StringBuilder myJoins = new StringBuilder() ;
                    for (int i = 0; i < beans.mybuy_record.size(); i++) {
                        myJoins.append(beans.mybuy_record.get(i)+"  ");
                    }
                    ftNumbers.setText(myJoins.toString());


                }
                if (beans.open_state == 1) {  // 抽奖中
                    rlNext.setVisibility(View.GONE);
                    llOn.setVisibility(View.VISIBLE);
                    tvStasus.setText("进行中");
                    rlOn.setVisibility(View.VISIBLE);
                    rlFinish.setVisibility(View.GONE);
                    tvQishu.setText(beans.activity_progress.fvid);
                    tvRenci.setText(beans.activity_progress.total_num);
                    tvRemain.setText(beans.activity_progress.last_num);
                    progress.setSecondaryProgress((int) (beans.activity_progress.openratio * 100 * 1.0));

                } else { //抽奖结束
                    tvStasus.setText("已揭晓");
                    rlOn.setVisibility(View.GONE);
                    rlFinish.setVisibility(View.VISIBLE);
                    rlNext.setVisibility(View.VISIBLE);
                    llOn.setVisibility(View.GONE);
                    String name=String.format("获奖者 ：<font color=\"##15B56F\">%s",beans.open_info.nickname+" ("+beans.open_info.address+")");
                    tvName.setText(Html.fromHtml(name));
                    tvId.setText("用户id:"+beans.open_info.userid+"(用户唯一标识)");
                    tvQihao.setText("期号："+ beans.open_info.fvid);
                    String join=String.format("本次参与 ：<font color=\"#FF0E41\">%s", beans.open_info.partake_num);
                    tvFinishRenci.setText(Html.fromHtml(join)+"人次");
                    tvFinishTime.setText("揭晓时间："+ beans.open_info.opentime);
                    tvLuckyNum.setText("幸运号码："+beans.open_info.lucky_num);
                    ImageLoaderUtils.display(ivImg,beans.open_info.face);

                }

                List<DuoBaoDetailsEntity.AllRecordBean> beanList = beans.all_record;
                recyclerview.loadMoreComplete();
                // 下拉刷新
                if (mIsRefreshOrLoadMore == 0) {
                    recyclerview.refreshComplete();
                    adapter.clear();
                }

                if (EmptyUtils.isNotEmpty(beanList)) {
                    bean = beanList;
                    adapter.addAll(bean);
                } else if (mIsRefreshOrLoadMore == 0) {
//                    statusEmpty();
                    return;
                }

                if (EmptyUtils.isEmpty(beanList)) {
                    recyclerview.setNoMore(true);
                } else {
                    mIsHasNoData = beanList.size() < mPageSize;
                    recyclerview.setNoMore(mIsHasNoData);
                }
                adapter.notifyDataSetChanged();
                recyclerview.refreshComplete();
                recyclerview.loadMoreComplete();
                if (mIsRefreshOrLoadMore == 0) {
                    dismissProgressDialog();
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                adapter.notifyDataSetChanged();
                recyclerview.refreshComplete();
                recyclerview.loadMoreComplete();
                if (mIsRefreshOrLoadMore == 0) {
                    dismissProgressDialog();
                }
            }
        });


        DuoBaoDetailMethods.getInstance().duobaoGoods(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID), tempItemBean.gid + "", tempItemBean.vid + "", tempItemBean.fvid);
        rxManager.add(subscriber);
    }

    private void setRecyclerView() {
//        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
       /* GridLayoutManager layoutManager = new GridLayoutManager(context, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);*/
        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 1)));
        recyclerview.setHasFixedSize(true);
        recyclerview.setRefreshing(false);


//        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.HORIZONTAL, (int) SizeUtils.dp2px(context, 1)));
//        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 1)));
        recyclerview.setLoadMoreEnabled(true);
        adapter = new JoinRecordAdapter(context, bean);
//        adapter.setOnItemClickSeclect(this);
        recyclerview.setAdapter(adapter);
        recyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mPageIndex = 1;
                mIsRefreshOrLoadMore = 0;
                gotoHttpRep();
            }

            @Override
            public void onLoadMore() {
                if (mIsHasNoData) {
                    recyclerview.loadMoreComplete();
                    recyclerview.setNoMore(true);
                    return;
                }
                mPageIndex++;
                mIsRefreshOrLoadMore = 1;
                gotoHttpRep();
            }
        });
    }


}
